import React, { Component } from "react"
import { messages, queryCurrencyPrecision } from "share/common"
import { Popover, notification } from 'antd'
import moment from "moment"
import BacklashModal from "./backlash-modal";
import httpFetch from "share/httpFetch";
import selectorData from 'share/selectorData'

const DataHoc = WrappedComponent => {

  class Hoc extends Component {

    setWrappedInstance = ref => {
      this.wrappedInstance = ref;
    };

    searchForm = [
      {
        id: 'formOIDs',
        component: 'MultiSelectorV2',
        label: messages('expense-14.key220')/*表单类型*/,
        props: {
          type: 'authority_form',
          params: { formType: 1002 },
          labelKey: 'formName',
          isShowSelectAll: true
        },
        parser: value => ({
          formOIDs: value ? value.map(item => item.formOID) : null
        })
      },
      {
        id: 'businessCode', label: messages('common.document.code')/*单号*/, component: 'Input',
        dataIndex: 'businessCode'
      }
    ];

    financeApproval = [{
      id: 'financeApproval', label: messages('expense-14.key469')/*审核日期*/, component: 'DateRangePicker',
      parser: value => ({
        auditedApprovalStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        auditedApprovalEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : undefined
      })
    }];

    recoil = [{
      id: 'recoil', label: messages('expense-14.key470')/*反冲日期*/, component: 'DateRangePicker',
      parser: value => ({
        recoilBeginDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        recoilEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : undefined
      })
    }, {
      id: 'userOID', label: messages('expense-14.key471')/*反冲人*/,
      component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('expense-14.key472')/*反冲人姓名/工号*/,
        type: 'user',
        selectorItem: {
          ...selectorData['user'],
          url: `/api/user/documents/review/search`,
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('expense-14.key225')/*待离职员工*/ :
                  messages('expense-14.key226')/*离职员工*/}）`
              ) :
              ''
          )}`)
        },
        searchIfKeywordIsNull: false
      },
    }];

    getSearchForm = (type, entityType) => {
      return this.searchForm.map(item => {
        item.id === 'formOIDs' && (item.props.params.formType = entityType);
        return item
      }).concat(type === 'backlash' ? this.financeApproval : this.recoil)
    };

    columns = [
      { title: messages('common.applicant')/*申请人*/, dataIndex: 'applicantName' },
      { title: messages('common.user.id')/*工号*/, dataIndex: 'employeeID' },

    ];

    getColumns = (type, entityType) => {
      return this.columns.concat(type === 'backlash' ? [
        { title: messages('common.submit.date')/*提交日期*/, dataIndex: 'submittedDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-' },
        { title: messages('expense-14.key473')/*审核通过日期*/, dataIndex: 'lastAuditApprovalDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-' },
        { title: messages('expense-14.key220')/*表单类型*/, dataIndex: 'formName', render: value => <Popover content={value}>{value}</Popover> },
        { title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode', render: value => <Popover content={value}>{value}</Popover> },
        { title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode' },
        {
          title: entityType === 1002 ? messages('common.total.amount')/*总金额*/ : messages('expense-14.key474')/*借款金额*/, dataIndex: entityType === 1002 ? 'totalAmount' : 'paymentAmount',
          render: (value, record) => <Popover content={this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))}>{this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))}</Popover>,        },
        { title: messages('expense-14.key475')/*事由*/, dataIndex: 'title', render: value => value ? <Popover content={value}>{value}</Popover> : '-' },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operator',
          render: (value, record) => React.Component.prototype.checkNewAuth() ?
            <a onClick={e => this.handleBacklash(e, record, entityType)} >{messages('expense-14.key476')/*反冲*/}</a> :
            <span className='font-disabled' style={{cursor: 'not-allowed'}}>{messages('expense-14.key476')/*反冲*/}</span>
        }
      ] : [
        { title: messages('expense-14.key220')/*表单类型*/, dataIndex: 'formName', render: value => <Popover content={value}>{value}</Popover> },
        { title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode', render: value => <Popover content={value}>{value}</Popover> },
        { title: messages('expense-14.key471')/*反冲人*/, dataIndex: 'recoilUserName' },
        { title: messages('expense-14.key477')/*反冲时间*/, dataIndex: 'recoilDate', render: value => value ? moment(value).format('YYYY-MM-DD HH:mm') : '-' },
        { title: messages('expense-14.key478')/*反冲原因*/, dataIndex: 'recoilReason', render: value => <Popover content={value}>{value}</Popover> }
      ])
    };

    handleBacklash = (e, record, entityType) => {
      e.stopPropagation();
      BacklashModal.open(this).then(({data, closeModal, context}) => {
        return httpFetch.post(`/api/bill/recoil`, {
          entityType,
          entityOID: entityType === 3001 ? record.loanBillOid : record.entityOID,
          recoilReason: data
        }).then(() => {
          this.wrappedInstance.advancedTableRef.getList();
          notification.success({
            message: messages('expense-14.key479')/*反冲成功*/,
            description: ''
          });
        }).catch(e => {
          notification.error({
            message: messages('expense-14.key480')/*反冲失败*/,
            description: <div>{e.response.data.message}</div>
          });
        }).finally(() => {
          context.setState({ confirmLoading: false });
          closeModal();
        })
      })
    };

    render() {
      let props = { ...this.props, ref: this.setWrappedInstance };
      return (
        <WrappedComponent
          {...props}
          getColumns={this.getColumns}
          getSearchForm={this.getSearchForm}
        />
      )
    }

  }

  return Hoc

};

export default DataHoc
